from typing import List

import crypto
import app.util.rpc as rpc


def get_tx_outputs(tx: dict) -> List[tuple]:
    vouts: list = tx['vout']
    outputs = list()
    for vout in vouts:
        script: dict = vout['scriptPubKey']
        script_type: str = script['type']
        if script_type == 'pubkey':
            asm: str = script['asm']
            parts = asm.split(' ')
            assert len(parts) == 2
            pubkey = parts[0]
            outputs.append((crypto.convert_pubkey_to_account(pubkey), vout['value']))
        else:
            outputs.append((
                script['address'] if 'address' in script else '',
                vout['value'] if 'value' in vout else 0
            ))
    return outputs


# def get_tx_inputs(tx: dict) -> List[tuple]:
#     inputs = list()
#     if is_coinbase(tx):
#         return inputs
#     for item in tx['vin']:
#         spent_txid: str = item['txid']
#         vout_num: int = item['vout']
#         spent_tx = cli.get_transaction(spent_txid)
#         vout_addresses = get_tx_outputs(spent_tx)
#         inputs.append(vout_addresses[vout_num])
#     return inputs


def get_spent_txids(tx: dict) -> List[str]:
    txids = list()
    for item in tx['vin']:
        spent_txid: str = item['txid']
        txids.append(spent_txid)
    return txids


def get_latest_txs(block_count: int) -> List[str]:
    txids = list()
    block_hash = rpc.get_latest_block_hash()
    for _ in range(block_count):
        block = rpc.get_block(block_hash, 1)
        txids += block['tx']
    return txids


def get_total_balance(tx: dict) -> float:
    outputs = get_tx_outputs(tx)
    total = 0
    for out in outputs:
        total += out[1]
    return total
